import { Component } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import * as moment from 'moment';
import * as _ from 'lodash';
import { Title } from '@angular/platform-browser';

import { ApiRequest } from 'service/ApiRequest';
import { SignalRService } from 'service/SignalRService';
import { HOT_PRODUCT } from 'utils/index';

@Component({
    selector: 'news-detail',
    templateUrl: './NewsDetail.html',
  }
)

export class NewsDetailComponent {

  news = {};

  signalRService: SignalRService = new SignalRService('forexHub');
  
  productList = HOT_PRODUCT;

  constructor(private route:ActivatedRoute, private apiRequest:ApiRequest, private title:Title) {

  }

  ngOnInit() {
    this.title.setTitle("新闻资讯");
    this.route.params.subscribe(data => {
      const id = data["id"];
      this.loadNew(id);
    });
    this.subscribe();
  }

  loadNew(id) {
    this.apiRequest.getNews(id).then((data) => {
      this.news = Object.assign({}, data, {
        Time: moment(data.Time * 1000).format("YYYY-MM-DD HH:mm:ss")
      });
    });
  }

  subscribe() {
    this.signalRService.registerOn("onNewBasicProductInfoStr", (symbol, data)=> {
			const list = data.split("-");
			const close = parseFloat(list[7]);
			const time = parseInt(list[1]);

      let floating = 0;
      let percent = '-';

      if (parseFloat(list[4]) !== 0 && parseFloat(list[5]) !== 0 && parseFloat(list[5]) !== 0) {
        floating = parseFloat(list[7])- parseFloat(list[4]);
        percent = (floating / parseFloat(list[4]) * 100).toFixed(2);
      }

      const quoteBasic = {
        Symbol: list[0],
        Time: parseInt(list[1]) * 1000,
        Volume: list[2],
        YesterdayClose: parseFloat(list[3]),
        DayOpen: parseFloat(list[4]),
        DayHigh: parseFloat(list[5]),
        DayLow: parseFloat(list[6]),
        CurrentPrice: parseFloat(list[7]),
        BuyPrice: parseFloat(list[8]),
        SellPrice: parseFloat(list[9]),
        floating: floating,
        percent: percent
      };

      const index = _.findIndex(this.productList, (item) => item['Symbol'] === symbol);
      if (index > -1) {
        this.productList[index]['quote'] = quoteBasic;  
      }
		});

    const newSymbols = this.productList.map(item => item.Symbol);
		this.signalRService.getConnection().done((data: any) => {
				this.signalRService.subscribe(newSymbols.join(';'));
		}).fail((error: any) => {  
				console.log('Could not connect ' + error);  
		});
  }

  unSubscribe() {
    const symbols = this.productList.map(item => item.Symbol);
    this.signalRService.unSubscribe(symbols);
  }

   ngOnDestroy() {
    this.unSubscribe();
	}
}